﻿using LiteDB;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LiteDb
{
    // 设备扩展
    public class DeviceExtra
    {
        public int id { get; set; } = -1;
        public int monitorPortId { get; set; } = -1;
        public string name { get; set; } = "DeviceName";
        public string extra { get; set; } = "";

        //  需要写一个转换函数(把object转换为DeviceExtra)
        public static DeviceExtra Convert(object obj)
        {
            try
            {
                if (obj == null)
                {
                    throw new ArgumentNullException(nameof(obj), "输入对象不能为空");
                }

                var json = obj.ToString();
                if (string.IsNullOrWhiteSpace(json))
                {
                    throw new ArgumentException("输入的JSON字符串不能为空或仅包含空白字符", nameof(obj));
                }

                var extra = JsonConvert.DeserializeObject<DeviceExtra>(json);
                if (extra == null)
                {
                    throw new Exception("反序列化结果为null");
                }

                return extra;
            }
            catch (Exception ex)
            {
                throw new Exception("转换失败: " + ex.Message);
            }
        }
        // DeviceExtra.Convert函数是object转换为DeviceExtra，需要新增一个函数MonitorDevice转为DeviceExtra
        public static DeviceExtra Convert(MonitorDevice device)
        {
            return new DeviceExtra
            {
                id = device.Id,
                monitorPortId = device.MonitorPortId,
                name = device.Name,
                extra = device.Extra,
            };
        }
    }   

}